using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using System.Threading.Tasks;
using WpfApp1.Core;
using System.Diagnostics;
using System.Linq;
using WPFMessageBox = System.Windows.MessageBox;
using WPFButton = System.Windows.Controls.Button;
using WPFTextBox = System.Windows.Controls.TextBox;
using WPFKeyEventArgs = System.Windows.Input.KeyEventArgs;
using WPFMouseEventArgs = System.Windows.Input.MouseEventArgs;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;

namespace WpfApp1
{
    public partial class HistoryWindow : MetroWindow
    {
        private readonly SyncService _syncService;
        private bool _forceClose;
        private IList<ClipboardItem>? _allItems;

        public HistoryWindow(SyncService syncService)
        {
            InitializeComponent();
            _syncService = syncService;
            StatusTextBlock.Text = "等待历史记录...";
        }

        public void UpdateHistory(IList<ClipboardItem> items)
        {
            Debug.WriteLine($"更新历史记录，共 {items.Count} 条");
            _allItems = items;
            ApplyFilter();
            UpdateListState();
            ClearStatusAfterDelay("历史记录已更新");
        }

        private void ApplyFilter()
        {
            if (_allItems == null) return;

            var selectedDevice = (DeviceFilter.SelectedItem as ComboBoxItem)?.Content.ToString();
            var searchText = SearchBox?.Text?.Trim().ToLower();
            
            var filteredItems = _allItems.AsEnumerable();

            // 搜索筛选
            if (!string.IsNullOrEmpty(searchText))
            {
                filteredItems = filteredItems.Where(i => 
                    i.Content.ToLower().Contains(searchText) ||
                    i.FormattedTime.ToLower().Contains(searchText) ||
                    i.DeviceDisplayName.ToLower().Contains(searchText));
            }

            // 设备筛选
            if (selectedDevice == "电脑")
            {
                filteredItems = filteredItems.Where(i => i.IsCurrentDevice);
            }
            else if (selectedDevice == "手机")
            {
                filteredItems = filteredItems.Where(i => !i.IsCurrentDevice);
            }

            // 按时间排序
            filteredItems = filteredItems.OrderByDescending(i => i.Timestamp);

            HistoryListView.ItemsSource = filteredItems.ToList();
            UpdateListState();
        }

        private void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            ApplyFilter();
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            ApplyFilter();
        }

        private void DeviceFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplyFilter();
        }

        private void ClearStatusAfterDelay(string message, int delay = 2000)
        {
            StatusTextBlock.Text = message;
            var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(delay) };
            timer.Tick += (s, args) =>
            {
                StatusTextBlock.Text = string.Empty;
                timer.Stop();
            };
            timer.Start();
        }

        private void UpdateListState()
        {
            var items = HistoryListView.ItemsSource as IList<ClipboardItem>;
            if (items == null || !items.Any())
            {
                EmptyText.Visibility = Visibility.Visible;
                HistoryListView.Visibility = Visibility.Collapsed;
            }
            else
            {
                EmptyText.Visibility = Visibility.Collapsed;
                HistoryListView.Visibility = Visibility.Visible;
            }
        }

        private void ShowLoading(bool show)
        {
            LoadingRing.IsActive = show;
            LoadingRing.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
            HistoryListView.IsEnabled = !show;
        }

        public async Task RefreshHistoryAsync()
        {
            try
            {
                Debug.WriteLine("开始刷新历史记录...");
                StatusTextBlock.Text = "正在刷新...";
                ShowLoading(true);
                
                var items = await _syncService.GetHistoryAsync();
                _allItems = items;
                ApplyFilter();
                UpdateListState();
                
                Debug.WriteLine($"历史记录已刷新，共 {items.Count} 条");
                ClearStatusAfterDelay("刷新完成");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"刷新历史记录失败: {ex}");
                StatusTextBlock.Text = $"刷新失败: {ex.Message}";
                throw;
            }
            finally
            {
                ShowLoading(false);
            }
        }

        public void ForceClose()
        {
            _forceClose = true;
            Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!_forceClose)
            {
                e.Cancel = true;
                Hide();
            }
        }

        private async Task EnsureServiceConnectionAsync()
        {
            if (!_syncService.IsConnected)
            {
                Debug.WriteLine("等待服务连接...");
                StatusTextBlock.Text = "等待服务连接...";
                await _syncService.StartAsync();
            }
        }

        private async void Refresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StatusTextBlock.Text = "正在刷新...";
                await EnsureServiceConnectionAsync();
                await RefreshHistoryAsync();
                ClearStatusAfterDelay("刷新完成");
            }
            catch (Exception ex)
            {
                StatusTextBlock.Text = $"刷新失败: {ex.Message}";
            }
        }

        private async void Clear_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (WPFMessageBox.Show("确定要清空所有历史记录吗？此操作不可恢复！", "确认清空", 
                    MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    StatusTextBlock.Text = "正在清空所有历史记录...";
                    await EnsureServiceConnectionAsync();
                    await _syncService.ClearHistoryAsync();
                    await RefreshHistoryAsync();
                    ClearStatusAfterDelay("已清空所有历史记录");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"清空历史记录失败: {ex}");
                StatusTextBlock.Text = $"清空失败: {ex.Message}";
            }
        }

        private async void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (sender is WPFButton button && button.Tag is string itemId)
            {
                try
                {
                    StatusTextBlock.Text = "正在删除...";
                    await _syncService.DeleteHistoryItemAsync(itemId);
                    await RefreshHistoryAsync();
                    StatusTextBlock.Text = "删除完成";
                }
                catch (Exception ex)
                {
                    StatusTextBlock.Text = $"删除失败: {ex.Message}";
                }
            }
        }

        private void HistoryListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (HistoryListView.SelectedItem is ClipboardItem item)
            {
                try
                {
                    if (string.IsNullOrEmpty(item.Content))
                    {
                        StatusTextBlock.Text = "无法复制空内容";
                        return;
                    }

                    ClipboardMonitor.SetContent(item.Content);
                    StatusTextBlock.Text = "已复制到剪贴板";
                    
                    // 2秒后清除状态栏文本
                    var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
                    timer.Tick += (s, args) =>
                    {
                        StatusTextBlock.Text = string.Empty;
                        timer.Stop();
                    };
                    timer.Start();
                }
                catch (Exception ex)
                {
                    StatusTextBlock.Text = $"复制失败: {ex.Message}";
                }
            }
        }

        private async void ViewContent_Click(object sender, RoutedEventArgs e)
        {
            if (sender is WPFButton button && button.Tag is ClipboardItem item)
            {
                var dialog = new CustomDialog
                {
                    Title = "内容查看"
                };

                var closeButton = new WPFButton
                {
                    Content = "关闭",
                    Style = TryFindResource("MahApps.Styles.Button") as Style,
                    Margin = new Thickness(0, 10, 0, 0),
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Right
                };

                var panel = new DockPanel();
                panel.Children.Add(new WPFTextBox
                {
                    Text = item.Content,
                    IsReadOnly = true,
                    TextWrapping = TextWrapping.Wrap,
                    AcceptsReturn = true,
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    Height = 300,
                    Width = 600,
                    FontSize = 14,
                    Margin = new Thickness(20)
                });
                panel.Children.Add(closeButton);
                DockPanel.SetDock(closeButton, Dock.Bottom);

                dialog.Content = panel;

                closeButton.Click += async (s, args) =>
                {
                    await this.HideMetroDialogAsync(dialog);
                };

                await this.ShowMetroDialogAsync(dialog);
            }
        }

        private void HistoryListView_MouseEnter(object sender, WPFMouseEventArgs e)
        {
            if (e.OriginalSource is FrameworkElement element && 
                element.DataContext is ClipboardItem)
            {
                var parent = element.Parent as Grid;
                if (parent != null)
                {
                    var viewButton = parent.Children.OfType<WPFButton>().FirstOrDefault();
                    if (viewButton != null)
                    {
                        viewButton.Visibility = Visibility.Visible;
                    }
                }
            }
        }

        private void HistoryListView_MouseLeave(object sender, WPFMouseEventArgs e)
        {
            if (e.OriginalSource is FrameworkElement element && 
                element.DataContext is ClipboardItem)
            {
                var parent = element.Parent as Grid;
                if (parent != null)
                {
                    var viewButton = parent.Children.OfType<WPFButton>().FirstOrDefault();
                    if (viewButton != null)
                    {
                        viewButton.Visibility = Visibility.Collapsed;
                    }
                }
            }
        }

        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            await SendContent();
        }

        private async void InputBox_KeyDown(object sender, WPFKeyEventArgs e)
        {
            if (e.Key == Key.Enter && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                e.Handled = true;
                await SendContent();
            }
        }

        private async Task SendContent()
        {
            var content = InputBox.Text?.Trim();
            if (string.IsNullOrEmpty(content))
            {
                return;
            }

            try
            {
                await EnsureServiceConnectionAsync();
                await _syncService.UploadContentAsync(content);
                InputBox.Clear();
                await RefreshHistoryAsync();
            }
            catch (Exception ex)
            {
                StatusTextBlock.Text = $"发送失败: {ex.Message}";
            }
        }
    }
} 